package com;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class Bluetooth {
	private static final UUID ECHO_SERVER_UUID = new UUID("29913A2DEB9340cfBBB8DEEE26452197", false);

	public static void main(String[] args) {
		Bluetooth b = new Bluetooth();
		Main.txmy = "";
		try {
			b.init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void init() throws Exception {
		LocalDevice localDevice = LocalDevice.getLocalDevice();
		StringBuffer url = new StringBuffer("btspp://");
		url.append("localhost").append(':');
		url.append(ECHO_SERVER_UUID.toString());
		url.append(";name=Echo Server");
		url.append(";authorize=false");
		StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open(url.toString());
		ServiceRecord record = localDevice.getRecord(notifier);
		boolean isBTReady = true;
		while (true) {
			StreamConnection conn = null;
			try {
				conn = notifier.acceptAndOpen();
				new BluetoothHandler(conn);
			} catch (IOException e) {
				continue;
			}
		}

	}

	class BluetoothHandler implements Runnable {
		StreamConnection conn;

		public BluetoothHandler(StreamConnection conn) {
			this.conn = conn;
			new Thread(this).start();
		}

		@Override
		public void run() {
			try {
				DataInputStream input = conn.openDataInputStream();
				OutputStream out = conn.openOutputStream();
				DataOutputStream dos = new DataOutputStream(out);
				while (true) {
					
					String data = input.readUTF();
					data = Aes.Decrypt(data, Main.txmy);
					MsgObj obj = MsgObj.fromJson(data);
					
					if (!obj.getType().equals("3") && !obj.getType().equals("4")) {
						MsgHandler.sendMsg(obj);
						dos.writeUTF("1");
					} else if (obj.getType().equals("4")) {
						dos.writeUTF("1");
					} else {
						String url=Main.getUrl();
						dos.writeUTF(url == null ? "0" : url);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					conn.close();
				} catch (Exception e) {
				}
			}
		}

	}
}
